package com.demo.webapp.filter;

import java.io.IOException;

import com.demo.common.Utils;
import java.util.Locale;
import java.util.Map;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.jstl.core.Config;

import com.demo.webapp.config.Constants;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * 本地化过滤器
 * 依赖Spring Web的OncePerRequestFilter
 * 使每个请求调用一次本地化设置
 * 本地化设置：
 * ①、设置本地语言	-为Spring和Struts2的多语言包提供参数
 * ②、设置主题		-为Struts2的theme
 * 
 * @author ryuu.kk
 *
 */
public class LocaleFilter extends OncePerRequestFilter {

	/**默认主题**/
	protected static final String DEFAULT_THEME = "default_theme";
	
	@SuppressWarnings("unchecked")
	@Override
	protected void doFilterInternal(HttpServletRequest request,	HttpServletResponse response, FilterChain chain)
			throws ServletException, IOException {
		
		/********************************************************
		 * 														*
		 * 1、请求参数优先										*
		 * 2、未得到请求参数,使用session的本地化Locale				*
		 * 3、未得到请求参数,并且session中无Locale,使用默认Local	*
		 * 														*
		 ********************************************************/
		//通过请求参数取得本地编码
		String locale = request.getParameter("locale");
		//默认使用中文
        Locale preferredLocale = null;

        //分解区域和语言，组成Locale对象
        /*修改为使用工具类处理 at 2012-01-31
        if (locale != null) {
            int indexOfUnderscore = locale.indexOf('_');
            if (indexOfUnderscore != -1) {
                String language = locale.substring(0, indexOfUnderscore);
                String country = locale.substring(indexOfUnderscore + 1);
                preferredLocale = new Locale(language, country);
            } else {
                preferredLocale = new Locale(locale);
            }
        }*/
        HttpSession session = request.getSession(false);
        
        if (StringUtils.isNotEmpty(locale)) {
	    	preferredLocale = Utils.localeFromString(locale, Locale.CHINESE);
	        
	        //如果Session存在，以request的local参数作为本地化
	        if (session != null) {
	            if (preferredLocale == null) {
	                preferredLocale = (Locale) session.getAttribute(Constants.PREFERRED_LOCALE_KEY);
	            } else {
	                session.setAttribute(Constants.PREFERRED_LOCALE_KEY, preferredLocale);
	                //设置jstl的i18n配置,以后删除。
	                Config.set(session, Config.FMT_LOCALE, preferredLocale);
	            }
	            if (preferredLocale != null && !(request instanceof LocaleRequestWrapper)) {
	                request = new LocaleRequestWrapper(request, preferredLocale);
	                //为spring提供本地依据
	                LocaleContextHolder.setLocale(preferredLocale);
	            }
	        } 
        } else {
        	if (session != null) {
        		preferredLocale = (Locale) session.getAttribute(Constants.PREFERRED_LOCALE_KEY);
        		if (preferredLocale != null) {
        			request = new LocaleRequestWrapper(request, preferredLocale);
                    //为spring提供本地依据
                    LocaleContextHolder.setLocale(preferredLocale);
        		}
        	}
        }
        //javax.servlet.jsp.jstl.core.Config.FMT_LOCALIZATION_CONTEXT;
        //Config.FMT_LOCALIZATION_CONTEXT
		/********************************************************
		 * 														*
		 * 将配合如下主题选取：									*	
		 * <link rel="stylesheet" type="text/css" media="all" href="<c:url value='/styles/${appConfig["csstheme"]}/theme.css'/>" />
		 * 是一个application全局级别存储主题						*
		 * 														*
		 ********************************************************/
        //取得主题参数
        String theme = request.getParameter("theme");
        //这里需要有管理权限的人才可以可以处理[需要考虑用户个人自定义主题操作]
        if (theme != null) {
            Map<String, Object> config = (Map<String, Object>) getServletContext().getAttribute(Constants.CONFIG);
            config.put(Constants.CSS_THEME, theme);
        }

        chain.doFilter(request, response);

        // Reset thread-bound LocaleContext.
        LocaleContextHolder.setLocaleContext(null);
    }
}